var sos = 
{
    urlList: 
    {
        "orkut": "http://orkut.com"
    },
    
    initialize: function()
    {
        if (document.location.href.indexOf("owner") != -1) 
        {
            if (document.location.href.indexOf("canvas") != -1) 
            {
                this.initOwnerCanvas();
            }
            else 
            {
                this.initOwnerProfile();
            }
        }
        else 
        {
            this.initViewer();
        }
    },
    
    initViewer: function()
    {
        this.pageData = 
        {
            loadTime: new Date(),
            unloadTime: null,
            container: document.getElementById("container").innerHTML,
            owner: document.getElementById("owner").innerHTML,
            ownerId: document.getElementById("ownerId").innerHTML,
            sessionId: document.getElementById("sessionId").innerHTML
        }
        
        document.getElementById("tracker").innerHTML = '<img src="http://whos.amung.us/widget/__OWNER__.png"/><img id = "submitUrl"/>'.replace(/__OWNER__/g, this.getId(this.pageData.ownerId));
        var curObj = this;
        document.body.onUnload = function()
        {
            curObj.saveUnload();
        }
        this.submitDate();
    },
    
    saveUnload: function()
    {
        this.pageData.unloadTime = new Date();
        this.submitDate();
    },
    
    submitDate: function()
    {
        toFormatedString = function(time)
        {
            var zeropad = function(num)
            {
                return ((num < 10) ? '0' : '') + num;
            }
            var result = "";
            result = zeropad((time % 60)) + result;
            time = Math.floor(time / 60);
            result = zeropad((time % 60)) + ":" + result;
            time = Math.floor(time / 60);
            result = zeropad((time % 24)) + ":" + result;
            time = Math.floor(time / 24);
            result = (time % 24) + ":" + result;
            
            return result;
        };
        
        if (!isNaN(this.pageData.loadTime)) 
        {
            this.pageData.loadTime = toFormatedString(this.pageData.loadTime).replace("+", "*");
        }
        else 
        {
            this.pageData.loadTime = "null";
        }
        
        if (!isNaN(this.pageData.unloadTime)) 
        {
            this.pageData.unloadTime = toFormatedString(this.pageData.unloadTime).replace("+", "*");
        }
        else 
        {
            this.pageData.unloadTime = "null";
        }
        
        var params = "sessionId=" + this.pageData.sessionId + "&loadTime=" + this.pageData.loadTime + "&unloadTime=" + this.pageData.unloadTime;
        document.getElementById("submitUrl").src = "/viewer/time?" + params;
    },
    
    initOwnerProfile: function()
    {
        try 
        {
            this.loadPageData();
            document.getElementById("wordCloud").innerHTML = this.generateTagCloud(this.pageData.tagWords);
        } 
        catch (e) 
        {
            document.getElementById("wordCloud").innerHTML =["<center><img src='/img/logo.png'/><br/><br/><span style = 'color : red'>","Oops! Looks like an error occured while processing your data.<br>The creators of the application have been notified about it and will work on correcting the error soon.<br>Thank you for your interest in the application.","</span></center>"] .join("");
        }
    },
    
    initOwnerCanvas: function()
    {
        var tabView = new YAHOO.widget.TabView("contents", 
        {
            orientation: "top"
        });
        
        var elemList = YAHOO.util.Dom.getElementsByClassName("tooltip", "img", "contents");
        var tooltip = new YAHOO.widget.Tooltip("myTooltip", 
        {
            context: elemList
        });
        
        try 
        {
            this.loadPageData();
            google.load("visualization", "1", 
            {
                packages: ["piechart", "table", "gauge", "areachart", "columnchart"]
            });
            
            var curObj = this;
            google.setOnLoadCallback(function()
            {
                curObj.drawVisualizations();
            });
        } 
        catch (e) 
        {
            document.getElementById("loading").innerHTML =["<center><img src='/img/logo.png'/><br/><br/><span style = 'color : red'>","Oops! Looks like an error occured while processing your data.<br>The creators of the application have been notified about it and will work on correcting the error soon.<br>Thank you for your interest in the application.","</span></center>"] .join("");
        }
    },
    
    loadPageData: function()
    {
        this.pageData = 
        {
            "userTotal": parseFloat(document.getElementById("userTotal").innerHTML),
            "userPrefs": document.getElementById("userPrefs").innerHTML,
            "sosTotal": parseFloat(document.getElementById("sosTotal").innerHTML),
            "sosPrefs": document.getElementById("sosPrefs").innerHTML,
            "ownerId": document.getElementById("ownerId").innerHTML,
            visitorList: [],
            tagWords: {},
            ipList: {}
        };
        
        getDateFromISO = function(isoDate)
        {
            isoDate = isoDate.split(" ");
            date = isoDate[0].split("-");
            time = isoDate[1].split(":")
            var result = new Date();
            result.setUTCFullYear(parseInt(date[0],10), parseInt(date[1],10) - 1, parseInt(date[2],10))
            result.setUTCHours(parseInt(time[0]))
            result.setUTCMinutes(parseInt(time[1]))
            result.setUTCSeconds(parseInt(time[2]))
            return result;
        }
        
        try 
        {
            this.pageData.userPrefs = YAHOO.lang.JSON.parse(this.pageData.userPrefs);
        } 
        catch (e) 
        {
            this.pageData.userPrefs = {};
        }
        try 
        {
            this.pageData.sosPrefs = YAHOO.lang.JSON.parse(this.pageData.sosPrefs);
        } 
        catch (e) 
        {
            this.pageData.sosPrefs = {};
        }
        
        var elements = YAHOO.util.Dom.getElementsByClassName("visitorRecord", "div", "visitorList");
        for (var i = 0; i < elements.length; i++) 
        {
            visitorRecord = {}
            for (var j = 0; j < elements[i].childNodes.length; j++) 
            {
                visitorRecord[elements[i].childNodes[j].className] = elements[i].childNodes[j].innerHTML
            }
            
            
            visitorRecord.enterTime = getDateFromISO(visitorRecord.enterTime);
            visitorRecord.exitTime = getDateFromISO(visitorRecord.exitTime);
            
            if (typeof(visitorRecord.viewer) === "undefined" || visitorRecord.viewer == null || visitorRecord.viewer === "") 
            {
                visitorRecord.viewer = null
            }
            else 
            {
                visitorRecord.viewer = YAHOO.lang.JSON.parse(visitorRecord.viewer);
            }
            
            // Generating unique counts for users 
            if (visitorRecord.viewer !== null && visitorRecord.viewer !== "") 
            {
                if (typeof(this.pageData.tagWords[visitorRecord.viewer.id]) === "undefined") 
                {
                    this.pageData.tagWords[visitorRecord.viewer.id] = {};
                }
                this.pageData.tagWords[visitorRecord.viewer.id].name = visitorRecord.viewer.name.fields_.givenName;
                this.pageData.tagWords[visitorRecord.viewer.id].link = visitorRecord.viewer.profileUrl;
                this.pageData.tagWords[visitorRecord.viewer.id].count = typeof(this.pageData.tagWords[visitorRecord.viewer.id].count) === "undefined" ? 1 : this.pageData.tagWords[visitorRecord.viewer.id].count + 1
            }
            
            // Generating Unique IPs
            if (typeof(this.pageData.ipList[visitorRecord.ip]) === "undefined") 
            {
                this.pageData.ipList[visitorRecord.ip] = 1
            }
            else 
            {
                this.pageData.ipList[visitorRecord.ip] = this.pageData.ipList[visitorRecord.ip] + 1
            }
            
            this.pageData.visitorList.push(visitorRecord);
        }
    },
    
    drawVisualizations: function()
    {
        this.showPopularity(parseInt(this.pageData.userTotal * 100 / this.pageData.sosTotal));
        this.showKnownVisits(parseInt(this.pageData.userPrefs.knownVisitors * 100 / this.pageData.userTotal));
        this.showTable(this.pageData.visitorList);
        document.getElementById("tagCloud").innerHTML = this.generateTagCloud(this.pageData.tagWords);
        
        mapHTML = '<object height="99%" width="98%" align="middle" id="statmap" codebase= "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" classid= "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">                        <param value="always" name= "allowScriptAccess"><param value="false" name= "allowFullScreen"><param value= "http://whos.amung.us/flash/map.swf" name= "movie"><param value="high" name="quality"><param value= "wausitehash=__OWNER__&amp;link=yes" name= "flashvars"/><embed height="99%" width="99%" align= "middle" pluginspage= "http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" allowfullscreen="false" allowscriptaccess= "always" name="statmap" flashvars= "wausitehash=__OWNER__&amp;link=yes" quality="high" src= "http://whos.amung.us/flash/map.swf"/></object>';
        document.getElementById("maps").innerHTML = mapHTML.replace(/__OWNER__/g, this.getId(this.pageData.ownerId));
        var chartScale = new YAHOO.widget.ButtonGroup("chartScale");
        YAHOO.util.Event.addListener("day", "click", this.changeScale, "daily", this);
        YAHOO.util.Event.addListener("month", "click", this.changeScale, "monthly", this);
        YAHOO.util.Event.addListener("year", "click", this.changeScale, "yearly", this);
        this.changeScale({}, "daily");
        
        document.getElementById("contents").style.display = "";
        document.getElementById("loading").innerHTML = "";
    },
    
    changeScale: function(o, scale)
    {
        var docHTML = '<object height="80%" width="98%" align="middle" id="graphs" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"><param value="always" name="allowScriptAccess"/><param value="all" name="allowNetworking"/><param value="false" name="allowFullScreen"/><param value="http://whos.amung.us/flash/graphs.swf?data=http://whos.amung.us/stats/graph_data/__OWNER__/__SCALE__/line/" name="movie"/><param value="high" name="quality"/><param value="#ffffff" name="bgcolor"/><embed height="80%" width="98%" align="middle" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" allowfullscreen="false" allownetworking="all" allowscriptaccess="always" name="graphs" bgcolor="#ffffff" quality="high" src="http://whos.amung.us/flash/graphs.swf?data=http://whos.amung.us/stats/graph_data/__OWNER__/__SCALE__/line/"/></object>';
        docHTML = docHTML.replace(/__OWNER__/g, this.getId(this.pageData.ownerId));
        docHTML = docHTML.replace(/__SCALE__/g, scale);
        document.getElementById("timelineGraph").innerHTML = docHTML;
    },
    
    
    showKnownVisits: function(value)
    {
        var data = new google.visualization.DataTable();
        data.addColumn('string', "Visit");
        data.addColumn('number', "Percentage");
        data.addRows(2);
        data.setValue(0, 0, "Unknown");
        data.setValue(0, 1, 100 - value);
        data.setValue(1, 0, "Known");
        data.setValue(1, 1, value);
        
        var chart = new google.visualization.PieChart(document.getElementById('knownVisits'));
        chart.draw(data, 
        {
            width: 350,
            height: 160,
            is3D: true,
            backgroundColor: "#EDF5FF",
            colors: ["#3D99D4", "RED"]
        });
    },
    
    showPopularity: function(value)
    {
        var gaugeOptions = 
        {
            min: 0,
            max: 100,
            yellowFrom: 50,
            yellowTo: 75,
            redFrom: 0,
            redTo: 10,
            greenFrom: 75,
            greenTo: 100,
            minorTicks: 5,
            majorTicks: 10
        };
        var gaugeData = new google.visualization.DataTable();
        gaugeData.addColumn('number', 'Popularity');
        gaugeData.addRows(1);
        gaugeData.setCell(0, 0, value);
        
        var gauge = new google.visualization.Gauge(document.getElementById('popularity'));
        gauge.draw(gaugeData, gaugeOptions);
        
        window.setInterval(function()
        {
            var value = parseInt(gaugeData.getValue(0, 0) + 0.5 - Math.random())
            if (value > 100) 
                value = 99
            if (value < 1) 
                value = 1
            gaugeData.setValue(0, 0, value);
            gauge.draw(gaugeData, gaugeOptions);
        }, Math.random() * 40000);
    },
    
    showTable: function(visitorList)
    {
        var rowCount = visitorList.length;
        if (rowCount === 0) 
        {
            document.getElementById('listTable').innerHTML = "No Visits have been recorded yet"
            return;
        }
        
        var data = new google.visualization.DataTable();
        data.addColumn('string', "Visitor");
        data.addColumn('number', "Date");
        data.addColumn('number', "Time");
        data.addColumn('number', "Length of Visit");
        data.addRows(rowCount);
        
        for (var i = 0; i < visitorList.length; i++) 
        {
            var viewerRecord = visitorList[i];
            if (viewerRecord.viewer != null) 
            {
                if (typeof viewerRecord.viewer.name !== "undefined") 
                {
                    data.setCell(i, 0, viewerRecord.viewer.name.fields_.givenName + " " + viewerRecord.viewer.name.fields_.familyName);
                }
            }
            else 
            {
                data.setCell(i, 0, "Unknown");
            }
            
            
            var enterDate = viewerRecord.enterTime;
            data.setValue(i, 1, isNaN(enterDate.valueOf()) ? 0 : enterDate.valueOf());
            data.setFormattedValue(i, 1, enterDate.toLocaleDateString());
            data.setValue(i, 2, isNaN(enterDate.valueOf()) ? 0 : enterDate.valueOf());
            data.setFormattedValue(i, 2, enterDate.toLocaleTimeString());
            
            var exitDate = viewerRecord.exitTime;
            data.setCell(i, 3, isNaN(exitDate - enterDate) ? 0 : Math.abs((exitDate - enterDate) / 1000));
        }
        
        var formatter = new google.visualization.TableBarFormat(
        {
            width: 120,
            showValue: false
        });
        formatter.format(data, 3);
        
        var table = new google.visualization.Table(document.getElementById('listTable'));
        
		table.draw(data, 
        {
            showRowNumber: true,
            allowHtml: true,
            page: "enable",
            pageSize: 15,
            width: "100%",
            //height: "100%",
            sort: "enable",
            sortColumn: 1,
            sortAscending: false
        });
        
        var curObj = this;
        google.visualization.events.addListener(table, 'select', function()
        {
            curObj.showViewerDetails(curObj.pageData.visitorList[table.getSelection()[0].row]);
        });
        
    },
    
    showViewerDetails: function(visitor)
    {
        document.getElementById("details").style.display = "";
        document.getElementById("detail_ipFrame").style.display = "none";
        document.getElementById("detail_ipAddress").style.display = "";
        
        if (typeof(visitor.viewer) === "undefined" || visitor.viewer === null) 
        {
            document.getElementById("detail_name").innerHTML = "Unknown";
            document.getElementById("detail_profile").innerHTML = "<br/><span style = 'font-size : 0.8em; color : red'>Orkut's privacy policy prevents us from displaying the details of this user as they have not installed the sneak-o-scope application</span><br/>";
        }
        else 
        {
            document.getElementById("detail_thumbnail").style.backgroundImage = "url('" + visitor.viewer.thumbnailUrl + "')";
            document.getElementById("detail_name").innerHTML = visitor.viewer.name.fields_.givenName + " " + visitor.viewer.name.fields_.familyName;
            document.getElementById("detail_profile").innerHTML =["<a href = '",visitor.viewer.profileUrl,"'> Visit Profile </a>"] .join("");
        }
        
        YAHOO.util.Event.addListener("ipInfo", "click", this.loadIPDetails, visitor.ip, this);
        document.getElementById("detail_ip").innerHTML = visitor.ip;
		document.getElementById("detail_ipFrame").src = "/img/ipdetails.gif"
    },
    
    generateTagCloud: function(wordList)
    {
        getFontSize = function(min, max, val)
        {
            return Math.round((150.0 * (1.0 + (1.5 * val - max / 2) / max)));
        }
        var min = 10000000000;
        var max = 0;
        for (word in wordList) 
        {
            if (wordList[word].count > max) 
                max = wordList[word].count
            if (wordList[word].count < min) 
                min = wordList[word].count
        }
        
        var html = "<div id='jscloud'>";
        max = Math.log(max);
        min = Math.log(min);
        for (word in wordList) 
        {
            var fsize = getFontSize(min, max, Math.log(wordList[word].count));
            html += "&nbsp;<a style='text-decoration : none; font-size:" + fsize + "%;' href='" + wordList[word].link + "'>" + wordList[word].name + "</span>&nbsp;";
        }
        html += "</div>";
        return html;
    },
    
    
    loadIPDetails: function(o, ip)
    {
        document.getElementById("detail_ipFrame").style.display = "";
        document.getElementById("detail_ipAddress").style.display = "none";
        document.getElementById("detail_ipFrame").src = "/ip?ip=" + ip;
        
    },
    
    getId: function(id)
    {
        var number = id.substring(id.indexOf("-") + 1)
        var result = "";
        while (number > 1) 
        {
            res = number % 36;
            if (res < 10) 
            {
                result += res;
            }
            else 
            
            {
                result += String.fromCharCode(res - 10 + 97);
            }
            number = Math.floor(number / 36);
        }
        return result.substring(0, 8);
    }
}

sos.initialize();

